package com.cloudinnov.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.cloudinnov.logic.AlarmWorkOrdersLogic;
import com.cloudinnov.model.AlarmWorkOrders;
import com.cloudinnov.utils.CommonUtils;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 客户工单webSocket
 * @author chengning
 * @date 2016年4月11日上午11:13:03
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
@ServerEndpoint("/alarm/{customer}/{language}")
public class CustomerAlarmWebsocket {
	private static Logger logger = LoggerFactory.getLogger(CustomerAlarmWebsocket.class);
	private static final String FAULT_REDIS_SPILT = "_";
	private String random;
	// 静态变量，用来记录当前在线连接数。
	private static int onlineCount = 0;
	// 用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
	public static ConcurrentMap<String, CustomerAlarmWebsocket> webSocketMap = new ConcurrentHashMap<String, CustomerAlarmWebsocket>();
	// 用来发送数据
	private Session session;
	private static WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
	private static AlarmWorkOrdersLogic alarmWorkOrdersLogic = (AlarmWorkOrdersLogic) context
			.getBean("alarmWorkOrdersLogic");
	@Autowired
	AlarmWorkOrdersLogic alarmWorkOrdersLogics;

	/**
	 * 打开连接时触发
	 * @param relationId
	 * @param userCode
	 * @param session
	 * @throws IOException
	 * @throws JsonProcessingException
	 */
	@OnOpen
	public void onOpen(@PathParam("customer") String customer, @PathParam("language") String language, Session session)
			throws JsonProcessingException, IOException {
		this.session = session;
		this.random = CommonUtils.getUUID();
		webSocketMap.put(customer + FAULT_REDIS_SPILT + language + FAULT_REDIS_SPILT + random, this);
		// 连接人数加1
		addOnlineCount();
		logger.debug("告警推送开始连接:" + customer + FAULT_REDIS_SPILT + language + FAULT_REDIS_SPILT + random);
		AlarmWorkOrders alarm = new AlarmWorkOrders();
		alarm.setCustomerCode(customer);
		alarm.setOrderStatus(0);
		alarm.setLanguage(language);
		List<AlarmWorkOrders> customerAlarmList = alarmWorkOrdersLogic.selectListWhere(alarm);
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_NULL);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("model", customerAlarmList);
		webSocketMap.get(customer + FAULT_REDIS_SPILT + language + FAULT_REDIS_SPILT + random)
				.sendMessage(mapper.writeValueAsString(map));
	}
	/**
	 * 收到客户端消息时触发 onMessage
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param select
	 * @param @param token
	 * @param @param message 参数
	 * @return void 返回类型
	 */
	@OnMessage
	public void onMessage(@PathParam("customer") String customer, @PathParam("language") String language,
			String message) {
	}
	/**
	 * 异常时触发
	 * @param relationId
	 * @param userCode
	 * @param session
	 */
	@OnError
	public void onError(@PathParam("customer") String customer, @PathParam("language") String language,
			Throwable throwable, Session session) {
		logger.error("告警推送异常:" + customer + FAULT_REDIS_SPILT + language + FAULT_REDIS_SPILT + random);
		logger.error(throwable.getMessage(), throwable);
	}
	/**
	 * 关闭连接时触发
	 * @param relationId
	 * @param userCode
	 * @param session
	 */
	@OnClose
	public void onClose(@PathParam("customer") String customer, @PathParam("language") String language,
			Session session) {
		webSocketMap.remove(customer + FAULT_REDIS_SPILT + language + FAULT_REDIS_SPILT + random);
		subOnlineCount(); // 在线数减1
		logger.debug("告警推送连接关闭:" + customer + FAULT_REDIS_SPILT + language + FAULT_REDIS_SPILT + random);
	}
	/**
	 * 推送工单消息
	 * @param message
	 * @throws IOException
	 */
	public synchronized void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
	}
	public static synchronized int getOnlineCount() {
		return onlineCount;
	}
	public static synchronized void addOnlineCount() {
		CustomerAlarmWebsocket.onlineCount++;
	}
	public static synchronized void subOnlineCount() {
		CustomerAlarmWebsocket.onlineCount--;
	}
}
